#include "DatabaseHandler.h"
#include <iostream>

DatabaseHandler::DatabaseHandler() : db(nullptr) {
}

DatabaseHandler::~DatabaseHandler() {
    close();
}

bool DatabaseHandler::open(const std::string& dbPath) {
    // 如果已经打开，先关闭
    if (db) {
        close();
    }
    
    // 打开数据库
    int rc = sqlite3_open(dbPath.c_str(), &db);
    if (rc != SQLITE_OK) {
        std::cerr << "Cannot open database: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        db = nullptr;
        return false;
    }
    
    std::cout << "Successfully opened database: " << dbPath << std::endl;
    
    return true;
}

void DatabaseHandler::close() {
    if (db) {
        sqlite3_close(db);
        db = nullptr;
    }
}

bool DatabaseHandler::isOpen() const {
    return db != nullptr;
}

// 回调函数，用于处理平台类型查询结果
static int platformTypesCallback(void* data, int argc, char** argv, char** azColName) {
    auto* platformTypes = static_cast<std::map<std::string, std::string>*>(data);
    
    if (argc >= 2 && argv[0] && argv[1]) {
        // 第一列是平台类型名称，第二列是参数（声明字符串）
        (*platformTypes)[argv[0]] = argv[1];
    }
    
    return 0;
}

bool DatabaseHandler::loadPlatformTypes(std::map<std::string, std::string>& platformTypes) {
    if (!db) {
        std::cerr << "Database not open" << std::endl;
        return false;
    }
    
    // 检查platform表是否存在
    std::cout << "Checking if platform table exists..." << std::endl;
    char* errMsg = nullptr;
    int tableExists = 0;
    std::string checkTableSQL = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='platform';";
    
    int rc = sqlite3_exec(db, checkTableSQL.c_str(), 
        [](void* data, int argc, char** argv, char** colNames) -> int {
            int* result = static_cast<int*>(data);
            if (argc > 0 && argv[0]) {
                *result = atoi(argv[0]);
            }
            return 0;
        }, &tableExists, &errMsg);
    
    if (rc != SQLITE_OK) {
        std::cerr << "SQL error when checking table: " << (errMsg ? errMsg : "unknown error") << std::endl;
        if (errMsg) sqlite3_free(errMsg);
        return false;
    }
    
    if (tableExists == 0) {
        std::cerr << "Error: Platform table does not exist in the database!" << std::endl;
        return false;
    }
    
    std::cout << "Platform table exists, checking for records..." << std::endl;
    
    // 检查表中有多少记录
    int recordCount = 0;
    std::string countSQL = "SELECT count(*) FROM platform;";
    
    rc = sqlite3_exec(db, countSQL.c_str(), 
        [](void* data, int argc, char** argv, char** colNames) -> int {
            int* result = static_cast<int*>(data);
            if (argc > 0 && argv[0]) {
                *result = atoi(argv[0]);
            }
            return 0;
        }, &recordCount, &errMsg);
    
    if (rc != SQLITE_OK) {
        std::cerr << "SQL error when counting records: " << (errMsg ? errMsg : "unknown error") << std::endl;
        if (errMsg) sqlite3_free(errMsg);
        return false;
    }
    
    std::cout << "Found " << recordCount << " records in the platform table." << std::endl;
    
    if (recordCount == 0) {
        std::cerr << "Warning: Platform table exists but contains no records!" << std::endl;
        return true; // 返回true但没有实际数据
    }
    
    // 执行查询，从platform表中获取所有平台类型
    std::cout << "Executing SELECT query to retrieve platform types..." << std::endl;
    const char* sql = "SELECT platformType, param FROM platform";
    
    // 执行查询并使用回调函数处理结果
    bool result = executeQuery(sql, platformTypesCallback, &platformTypes);
    
    if (!result) {
        std::cerr << "Failed to execute SELECT query!" << std::endl;
        return false;
    }
    
    std::cout << "Successfully loaded " << platformTypes.size() << " platform types from database." << std::endl;
    return true;
}

bool DatabaseHandler::executeQuery(const std::string& sql, 
                                  int (*callback)(void*, int, char**, char**), 
                                  void* data) {
    if (!db) {
        std::cerr << "Database not open" << std::endl;
        return false;
    }
    
    std::cout << "Executing SQL: " << sql.substr(0, 50) << (sql.length() > 50 ? "..." : "") << std::endl;
    
    char* errMsg = nullptr;
    int rc = sqlite3_exec(db, sql.c_str(), callback, data, &errMsg);
    
    if (rc != SQLITE_OK) {
        std::cerr << "SQL error (code " << rc << "): " << (errMsg ? errMsg : "unknown error") << std::endl;
        std::cerr << "Full SQL: " << sql << std::endl;
        
        // 获取更多的数据库信息
        std::cerr << "SQLite version: " << sqlite3_libversion() << std::endl;
        std::cerr << "Database file status: " << (sqlite3_db_readonly(db, "main") ? "read-only" : "read-write") << std::endl;
        
        if (errMsg) {
            sqlite3_free(errMsg);
        }
        return false;
    }
    
    std::cout << "SQL executed successfully" << std::endl;
    return true;
} 